// pages/book/book-detail/index.js
import {BookModel} from "../../../modules/book.js";
import {LikeModel} from "../../../modules/like.js";
let bookMode=new BookModel();
let likeMode=new LikeModel();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    comments:[],
    book:null,
    likeStatus:true,
    likeCount:0,
    posting:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading();
    const id = options.id;
    const detail=bookMode.getDetail(id);
    const comments=bookMode.getComments(id);
    const likeStatus=bookMode.getLikeStatus(id);
    //all 等一块加载完后执行回掉
    //race 竞争 最快的执行完毕执行回掉
    Promise.all([detail,comments,likeStatus])
      .then((res)=>{
        this.setData({
          book:res[0],
          comments:res[1].comments,
          likeStatus:res[2].like_status,
          likeCount:res[2].fav_nums
        })
        wx.hideLoading();
      });
      /*
    detail.then((res)=>{
      this.setData({
          book:res
      })
    });
    comments.then((res)=>{
      this.setData({
        comments:res.comments
      })
    })
    likeStatus.then((res)=>{
      this.setData({
        likeStatus:res.like_status,
        likeCount:res.fav_nums
      })
    })
    */
  },
  onLike:function(e){
    likeMode.onlike(e.detail.behavior, this.data.book.id, 400); //400是书籍
  },
  onFakePost:function(){
    this.setData({
      posting:true
    })
  },
  onCancel:function(){
    this.setData({
      posting:false
    })
  },
  onPost:function(e){
    const comment=e.detail.text || e.detail.value;
    bookMode.postComment(this.data.book.id,comment)
    .then(res=>{
      wx.showToast({
        title:"+1",
        icon:"none"
      })
      this.data.comments.unshift({
        content:comment,
        nums:1
      });

      this.setData({
        comments:this.data.comments,
        posting:false
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})